#include "BaseCharacter.h"
#include "CEvent.h"
#include "../wrappers/CSGD_EventSystem.h"


CBaseCharacter::CBaseCharacter(void)
{
	m_nCharType		= CHAR_BASE;
	m_nHitPoints	= 100;
	m_nAttackDamage	= 10;
	m_nAttackRange	= 10;
	m_fAttackSpeed	= 1.0f;
	m_fBaseMoveSpeed= 100.0f;
	m_fHitStun		= 0.2f;
	m_fSlowDuration	= 0.0f;
	m_bIsSlowed		= false;

}


CBaseCharacter::CBaseCharacter( int HP, int AD, int AR, float AS,
							   float MS, float HS, int type )
	: m_nBaseHitPoints(HP), m_nAttackDamage(AD),
	  m_nAttackRange(AR), m_fAttackSpeed(AS),
	  m_fHitStun(HS), m_nCharType(type), CBaseObject()
{
	SetCharType( CHAR_BASE );
	m_nHitPoints	= m_nBaseHitPoints;
	m_fBaseMoveSpeed= MS;
	m_fMoveSpeed	= m_fBaseMoveSpeed;
	m_fSlowDuration = 0.0f;
	m_bIsSlowed		= false;
	m_fJumpVelocity = 0.0f;
	m_fMoveSpeed	= 150.0f;

	SetMoveDir();
}


CBaseCharacter::~CBaseCharacter(void)
{

}


void CBaseCharacter::Update( float fElapsedTime )
{
	//if( GetPosition().fZ + float(GetHeight()/2) < 290 )
	//	SetZPosition( 290 - float(GetHeight()/2) );


	if( m_fSlowDuration >= 0.01f )
	{
		m_fSlowDuration -= fElapsedTime;
	
	}
	else if( GetMoveSpeed() != m_fBaseMoveSpeed )
	{
		SetMoveSpeed( m_fBaseMoveSpeed );
		m_fSlowDuration = 0.0f;
	}


	if( IsGrounded() == false )
	{
		m_fJumpVelocity += GRAVITY * fElapsedTime;
		SetYPosition( GetPosition().fY + m_fJumpVelocity * fElapsedTime );
		
	}
	if( GetPosition().fY < 0.0f )
	{
		CSGD_EventSystem::GetInstance()->SendEvent("grounded", this);
	}

	SetPosition( GetPosition() + ( GetVelocity() * fElapsedTime ) );
	CBaseObject::Update( fElapsedTime );
}


void CBaseCharacter::Render( void )
{

}


void CBaseCharacter::HandleEvent( CEvent* pEvent )
{
	if( pEvent->GetEventID() == "grounded" &&
		pEvent->GetParam() == this )
	{
		m_fJumpVelocity = 0.0f;
		SetYPosition( 0.0f );
		SetGrounded( true );
	}
}


bool CBaseCharacter::CheckCollision( IObject* pOther )
{
	if( CBaseObject::CheckCollision( pOther ) == true && dynamic_cast< CBaseCharacter* >( pOther ) != nullptr
		&& pOther != this )
	{
		
		CBaseCharacter* pOtherChar = dynamic_cast< CBaseCharacter* >( pOther );
	
		pOtherChar->SetMoveSpeed( 0.0f );
		pOtherChar->Slow( m_fHitStun, 1.0f );

		tVector3D knockback = (pOtherChar->GetMoveDir() - this->GetMoveDir()) * 0.1f;
		pOtherChar->Knockback( knockback );

		return true;
	}
	else
		return false;
}


void CBaseCharacter::Jump( float fJumpVelocity )
{
	SetJumpVelocity( fJumpVelocity );
	SetGrounded( false );
}

void CBaseCharacter::Knockback( tVector3D knockback )
{
	SetPosition( this->GetPosition() - knockback );
}


void CBaseCharacter::Slow( float fDuration, float fPercentSlow )
{
	m_fSlowDuration = fDuration;
	SetMoveSpeed( GetMoveSpeed() - GetMoveSpeed() * fPercentSlow );
	m_bIsSlowed = true;
}

void CBaseCharacter::SetMoveDir( float fX, float fY, float fZ )
{
	m_tMoveDir.fX = fX;
	m_tMoveDir.fY = fY;
	m_tMoveDir.fZ = fZ;

}


tVector3D CBaseCharacter::GetVelocity( void )
{
	return m_tMoveDir * m_fMoveSpeed;
}
